#!/usr/bin/env python
# -*- coding:utf-8 -*-

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from bs4 import BeautifulSoup
from xlwt import Workbook

id = {
    'qq': '41573432',
    'code': '*******',
    'areas': ['艾欧尼亚', '诺克萨斯', '战争学院', '男爵领域']
}


def main(driver, url, fname):
    try:
        driver.get(url)
        driver.maximize_window()
        driver.switch_to.default_content()
        driver.find_element_by_id('dologin').click()
        driver.switch_to.frame('loginIframe')
        driver.find_element_by_id('switcher_plogin').click()
        time.sleep(1)
        driver.find_element_by_id('u').clear()
        driver.find_element_by_id('u').send_keys(id.get('qq'))
        driver.find_element_by_id('p').clear()
        driver.find_element_by_id('p').send_keys(id.get('code'))
        driver.find_element_by_id('login_button').click()
        time.sleep(1)
        driver.switch_to.default_content()

        areas = id.get('areas')
        if type(areas) == list:
            xlsFile = Workbook(encoding='utf-8')
            table = xlsFile.add_sheet('LOL已有皮肤')
            for i in range(len(areas)):
                time.sleep(1)
                try:
                    driver.find_element_by_id('noBind').click()
                except:
                    driver.find_element_by_id('isBind').click()
                time.sleep(1)
                LOLAreas = Select(
                    driver.find_element_by_id('areaContentId_lol'))
                time.sleep(1)
                for option in LOLAreas.options:
                    if areas[i] in option.text:
                        LOLAreas.select_by_visible_text(option.text)
                        time.sleep(1)
                        driver.find_element_by_id(
                            'confirmButtonId_lol').click()
                        driver.switch_to.alert.accept()
                        time.sleep(1)
                        html = driver.page_source
                        soup = BeautifulSoup(html, 'lxml')
                        skins = soup.select('li[class=""] > b')
                        for j in range(len(skins)):
                            if j == 0:
                                table.write(j, i, areas[i])
                            table.write(j + 1, i, skins[j].string)
                        break
            xlsFile.save(fname)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    driver = webdriver.Chrome()
    url = "http://lol.qq.com/act/a20180928DragonFist/awards.html"
    fname = "data.xls"
    main(driver, url, fname)
    driver.quit()
